package org.jeecg.config.shiro.authenticator;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.jeecg.config.shiro.JwtToken;

import java.util.Collection;

/**
 * @author by sean
 * @desc: 当配置了多个Realm时，我们通常使用的认证器是shiro自带的
 *  org.apache.shiro.authc.pam.ModularRealmAuthenticator，
 *  其中决定使用的Realm的是doAuthenticate()方法
 * @since 2024-09-02 星期一 16:44:53
 */
@Slf4j
public class UserModularRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("UserModularRealmAuthenticator:method doAuthenticate() 执行 ");
        // 判断getRealms()是否返回为空
        assertRealmsConfigured();

        // 所有Realm
        Collection<Realm> realms = getRealms();

        JwtToken jwtToken = (JwtToken) authenticationToken;
        String loginType = jwtToken.getLoginType();
        // 增加默认
        if(StrUtil.isEmpty(loginType)){
            loginType = "DEFAULT";
        }
        Realm realm = null;
        for (Realm realmItem : realms) {
            log.info("Realm>>>>{}", realmItem.getName());
            log.info("Realm>>>>{}", loginType);
            if (realmItem.getName().contains(loginType)) {
                realm = realmItem;
                break;
            }
        }
        if(realm == null){
            return null;
        }
        return doSingleRealmAuthentication(realm, authenticationToken);
    }
}
